/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.bot.server;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author phichidev
 */
public class WebServer {

    private HttpServer httpServer;
    private ArrayBlockingQueue<HttpExchange> httpExchanges = new ArrayBlockingQueue<HttpExchange>(100);
    private RequestHandlerRegistry requestHandlerRegistry = new RequestHandlerRegistry();
    private ExecutorService requestWorkerExecutorService;
    private String rootPath;

    public HttpServer getHttpServer() {
        return httpServer;
    }

    public RequestHandlerRegistry getRequestHandlerRegistry() {
        return requestHandlerRegistry;
    }

    public WebServer(int port, String rootPath) throws IOException {
        this(HttpServer.create(new InetSocketAddress(port), 0), rootPath);
    }

    public WebServer(HttpServer httpServer, String rootPath) {
        this.httpServer = httpServer;
        this.rootPath = rootPath;
    }

    public void start(int nThread) {
        httpServer.createContext("/", new HttpHandler() {

            @Override
            public void handle(HttpExchange exchange) throws IOException {
                try {
                    httpExchanges.put(exchange);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        });
        httpServer.setExecutor(null);
        httpServer.start();
        this.initRequestWorker(nThread);
        System.out.println("#INFO: Server start!");
    }

    protected void initRequestWorker(int nThread) {
        requestWorkerExecutorService = Executors.newFixedThreadPool(nThread);
        RequestHandler defaultRequestHandler = this.createDefaultRequestHandler();
        for (int i = 0; i < nThread; i++) {
            RequestWorker requestWorker = new RequestWorker(requestHandlerRegistry, httpExchanges);
            requestWorker.setDefaultRequestHandler(defaultRequestHandler);
            requestWorkerExecutorService.execute(requestWorker);
        }
    }

    protected RequestHandler createDefaultRequestHandler() {
        return new DefaultRequestHandler(rootPath);
    }
}
